<template>
  <div>
    <div class="chart-container">
      <div ref="totalFeeChart" class="chart" style="width: 100%; height: 300px;"></div>
    </div>
    <div class="chart-container">
      <div ref="totalDaysChart" class="chart" style="width: 100%; height: 300px;"></div>
    </div>
    <div class="chart-container">
      <div ref="totalUsageCountChart" class="chart" style="width: 100%; height: 300px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listReport } from '@/api/lh/report' // 引入你定义的 API 函数

export default {
  data() {
    return {
      chartData: {
        cars: [],
        totalFees: [],
        totalDays: [],
        totalUsageCounts: []
      }
    }
  },
  mounted() {
    this.fetchChartData()
  },
  watch: {
    chartData: {
      handler() {
        this.renderCharts()
      },
      deep: true
    }
  },
  methods: {
    async fetchChartData() {
      try {
        const response = await listReport({}) // 使用你定义的 API 函数来获取数据
        const data = response.data

        this.chartData.cars = data.map(item => item.car_id)
        this.chartData.totalFees = data.map(item => item.total_fee)
        this.chartData.totalDays = data.map(item => item.total_days_used)
        this.chartData.totalUsageCounts = data.map(item => item.total_usage_count)
      } catch (error) {
        console.error('Error fetching chart data', error)
      }
    },
    renderCharts() {
      // 渲染每个图表
      this.renderBarChart(this.$refs.totalFeeChart, 'Total Fee per Car', this.chartData.cars, this.chartData.totalFees)
      this.renderBarChart(this.$refs.totalDaysChart, 'Total Days Used per Car', this.chartData.cars, this.chartData.totalDays)
      this.renderBarChart(this.$refs.totalUsageCountChart, 'Total Usage Count per Car', this.chartData.cars, this.chartData.totalUsageCounts)
    },
    renderBarChart(el, title, xData, yData) {
      const chart = echarts.init(el)
      const option = {
        title: {
          text: title,
          subtext: '统计数据'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            interval: 0, // 确保所有标签都能显示
            rotate: 30 // 旋转标签，避免重叠
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: yData,
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: '#4CAF50' // 绿色
            }
          }
        ]
      }
      chart.setOption(option)
    }
  }
}
</script>

<style scoped>
.chart-container {
  margin-bottom: 20px;
}
.chart {
  width: 100%;
  height: 300px;
}
</style>
